<template>
  <div>
    <!--多条件查询及分页form -->
    <div style="float:left">
      <el-form :inline="true" :model="searchAdminRepairs" class="demo-form-inline">
        <div style="margin: 10px 0">
          <el-input
              placeholder="请输入设备名称"
              v-model="searchAdminRepairs.deviceName"
              style="width: 220px;"
              clearable>
          </el-input>
          <el-input
              placeholder="请输入设备型号"
              v-model="searchAdminRepairs.deviceModel"
              style="width: 225px;padding-left: 5px;"
              clearable>
          </el-input>
          <el-select v-model="searchAdminRepairs.deviceType" clearable placeholder="请选择设备类型" style="padding-left:5px;width: 225px;">
            <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
          <el-button type="warning" @click="getList(1)" style="margin-left: 5px;width: 70px;height: 40px;">查询</el-button>
        </div>
        <div style="margin: 10px 0">
          <!--    选择创建日期，不过options要绑定不同，不然查询选日期也会限制-->
          <el-date-picker class="createRepairsTime"
              v-model="searchAdminRepairs.creatTime"
              align="right"
              type="date"
              placeholder="选择创建日期"
              :picker-options="pickerOptionsOther">
          </el-date-picker>
          <!--    选择更新日期-->
          <el-date-picker class="updateRepairsTime"
              v-model="searchAdminRepairs.updateTime"
              align="right"
              type="date"
              placeholder="选择更新日期"
              :picker-options="pickerOptionsOther">
          </el-date-picker>
          <!--    选择首次使用日期-->
          <el-date-picker class="updateRepairsTime"
              v-model="searchAdminRepairs.startTime"
              align="right"
              type="date"
              placeholder="选择首次使用日期"
              :picker-options="pickerOptionsOther">
          </el-date-picker>
          <!--可加一个select选择，显示all，未休，已修，进行筛选list-->
          <el-select v-model="searchAdminRepairs.status" clearable placeholder="请选择设备状态" style="width: 180px;margin-left: 5px;">
            <el-option
                v-for="item in StatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </div>
      </el-form>
    </div>
    <el-button type="primary" @click="handleAdd" style="width: 105px;height:40px; margin-left: 10px;position: relative;left: -115px;top: 10px;">
      添加设备<i class="el-icon-circle-plus-outline"></i></el-button>
    <!-- list-->
      <!-- tableData.list相当于 response.data.list.list -->
      <el-table
          :data="tableData.list"
          style="width: 100%"
          v-loading="loading"
          :row-class-name="tableRowClassName"
      >
        <el-table-column
            type="index"
            label="序号"
            width="50">
        </el-table-column>
        <el-table-column prop="devicePic" label="设备图片" width="100">
          <template slot-scope="scope">
            <!-- 修改为：添加空值保护并提供默认图片 -->
            <el-image
                v-if="scope.row.inboundPic?.devicePic"
                :src="'http://localhost:8080/static/uploadImages/' + scope.row.inboundPic.devicePic"
                :preview-src-list="scope.row.inboundPic.devicePic ?
                  ['http://localhost:8080/static/uploadImages/' + scope.row.inboundPic.devicePic] : []"
                style="max-height: 40px; cursor: zoom-in;"
                class="custom-image"
            />
            <!-- 添加默认图片显示 -->
            <div v-else style="height:40px;line-height:40px;color:#999">
              暂无图片
            </div>
          </template>
        </el-table-column>
        <!-- 文字缩略显示，如果为空就显示横杠，避免异常，来源于网络-->
        <el-table-column
            prop="deviceName"
            label="设备名称"
            width="100">
          <template slot-scope="scope">
            <span :title="scope.row.deviceName || ''">
              {{ scope.row.deviceName ? (scope.row.deviceName.length > 5 ? scope.row.deviceName.substring(0,5) + '...' : scope.row.deviceName) : '——' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
            prop="deviceModel"
            label="设备型号"
            width="100">
          <template slot-scope="scope">
            <span :title="scope.row.deviceModel || ''">
              {{ scope.row.deviceModel ? (scope.row.deviceModel.length > 5 ? scope.row.deviceModel.substring(0,5) + '...' : scope.row.deviceModel) : '——' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
            prop="deviceType"
            label="设备类型"
            width="100">
        </el-table-column>
        <el-table-column
            prop="location"
            label="设备位置"
            width="100">
          <template slot-scope="scope">
            <span :title="scope.row.location || ''">
              {{ scope.row.location ? (scope.row.location.length > 5 ? scope.row.location.substring(0,5) + '...' : scope.row.location) : '——' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
            prop="user.userName"
            label="创建人"
            width="80">
          <template slot-scope="scope">
            <span :title="scope.row.user?.userName">
              {{ scope.row.user?.userName ? (scope.row.user.userName.length > 5 ? scope.row.user.userName.substring(0,5) + '...' : scope.row.user.userName) : '——' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="创建时间"
            :formatter="(row) => $options.filters.formatDateTime(row.creatTime)"
            width="100">
        </el-table-column>
        <el-table-column
            prop="admin.adminName"
            label="更新人"
            width="100">
          <template slot-scope="scope">
            <span :title="scope.row.admin?.adminName">
              {{ scope.row.admin?.adminName ? (scope.row.admin.adminName.length > 5 ? scope.row.admin.adminName.substring(0,5) + '...' : scope.row.admin.adminName) : '——' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
            prop="updateTime"
            label="更新时间"
            :formatter="(row) => $options.filters.formatDateTime(row.updateTime)"
            width="100">
        </el-table-column>
        <el-table-column
            prop="keepPeriod"
            label="保养周期月份"
            width="120">
        </el-table-column>
        <el-table-column
            prop="startTime"
            label="首次使用时间"
            :formatter="(row) => $options.filters.formatDate(row.startTime)"
            width="120">
        </el-table-column>
        <el-table-column
            prop="serviceLife"
            label="使用年限"
            width="80">
        </el-table-column>
        <el-table-column
            prop="status"
            label="设备状态"
            width="80">
        </el-table-column>
        <el-table-column prop="remark" label="备注">
          <template slot-scope="scope">
            <span :title="scope.row.remark || ''">
              {{ scope.row.remark ? (scope.row.remark.length > 3 ? scope.row.remark.substring(0,3) + '...' : scope.row.remark) : '——' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
            prop="keepStandard"
            label="设备保养手册"
            width="120">
          <template slot-scope="scope">
            <el-button @click="handleLook(scope.row)" type="text" size="small">查看手册</el-button>
          </template>
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="100">
          <template slot-scope="scope">
            <el-button @click="handleUpdate(scope.row)" type="text" size="small">修改</el-button>
            <el-button @click="handleDelete(scope.row)" type="text" size="small" style="color: #ED184E">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    <!--分页页码-->
    <div>
      <el-pagination class="pageNum"
         background
         layout="prev, pager, next"
         @current-change="handlePageNumChange"
         :page-size="tableData.pageSize"
         :total="tableData.total"
         :current-page="tableData.pageNum">
      </el-pagination>
    </div>
    <!-- 查看手册对话框 -->
    <el-dialog title="设备保养手册" :visible.sync="dialogFormVisible" width="30%" >
      <p><span style="color:#A9ADAF">设备名称:</span> {{device.deviceName}}</p>
      <p><span style="color:#A9ADAF">设备型号:</span> {{device.deviceModel}}</p>
      <p><span style="color:#A9ADAF">设备类型:</span> {{device.deviceType}}</p>
      <p><span style="color:#A9ADAF">设备使用年限:</span> {{device.serviceLife}}</p>
      <p style="color:#A9ADAF">设备保养详情:</p>
      <p>{{device.keepStandard}}</p><!-- 直接绑定数据 -->
      <p style="color:#A9ADAF">备注:</p>
      <p>{{device.remark}}</p>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="dialogFormVisible = false">退 出</el-button>
      </div>
    </el-dialog>
    <!-- 添加设备弹框 -->
    <el-dialog title="添加设备" :visible.sync="dialogFormVisibleByAdd" width="35%" >
      <el-form :model="addForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
<!--        <input type="hidden" v-model="addForm.creatBy">-->
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="addForm.deviceName" class="newInput"></el-input>
        </el-form-item>
        <el-form-item label="设备型号" prop="deviceModel">
          <el-input v-model="addForm.deviceModel" class="newInput"></el-input>
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="addForm.deviceType" placeholder="请选择设备类型" class="newSelect">
            <el-option label="监控" value="监控"></el-option>
            <el-option label="消防" value="消防"></el-option>
            <el-option label="照明" value="照明"></el-option>
            <el-option label="电梯" value="电梯"></el-option>
            <el-option label="给排水" value="给排水"></el-option>
            <el-option label="供暖" value="供暖"></el-option>
            <el-option label="电气" value="电气"></el-option>
            <el-option label="垃圾回收" value="垃圾回收"></el-option>
            <el-option label="净水设备" value="净水设备"></el-option>
            <el-option label="休闲健身" value="休闲健身"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备位置" prop="location">
          <el-input v-model="addForm.location" class="newInput"></el-input>
        </el-form-item>
        <el-form-item
            label="保养周期月份"
            prop="keepPeriod"
        >
          <el-input v-model.number="addForm.keepPeriod" autocomplete="off" class="newInput"></el-input>
        </el-form-item>
        <el-form-item
            label="设备使用年限"
            prop="serviceLife"
        >
          <el-input v-model.number="addForm.serviceLife" autocomplete="off" class="newInput"></el-input>
        </el-form-item>
        <!--一般的，添加新设备的设备状态默认为正常未过期，不可选择，先不要删除这段-->
<!--        <el-form-item label="设备状态" prop="status">-->
<!--          <el-select v-model="addForm.status" placeholder="请选择状态" class="newSelect">-->
<!--            <el-option label="正常" value="正常"></el-option>-->
<!--            <el-option label="异常" value="异常"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <!--图片上传,show-file-list是否显示文件列表-->
        <el-form-item label="设备图片">
          <el-upload
              class="avatar-uploader"
              :action="$basePath+'device/uploadImages'"
              :show-file-list="false"
              :accept="allowedPicExts"
              :headers="headers"
              :on-success="handlePicSuccess"
              :before-upload="beforePicUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <!-- 设备保养手册应该可上传图片或上传pdf ，但这里只上传文字-->
        <el-form-item label="设备保养手册" prop="keepStandard">
          <el-input type="textarea" v-model="addForm.keepStandard" class="newTextarea" style="padding-top: 20px;"></el-input>
        </el-form-item>
        <!-- 备注-->
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="addForm.remark" class="newTextarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleByAdd = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改设备弹框 -->
    <el-dialog title="修改设备信息" :visible.sync="dialogFormVisibleByUpdate" width="30%" >
      <el-form :model="updateForm" :rules="rules" ref="ruleForm" label-width="140px" class="demo-ruleForm">
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="updateForm.deviceName" class="newInput"></el-input>
        </el-form-item>
        <el-form-item label="设备型号" prop="deviceModel">
          <el-input v-model="updateForm.deviceModel" class="newInput"></el-input>
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="updateForm.deviceType" placeholder="请选择设备类型" class="newSelect">
            <el-option label="监控" value="监控"></el-option>
            <el-option label="消防" value="消防"></el-option>
            <el-option label="照明" value="照明"></el-option>
            <el-option label="电梯" value="电梯"></el-option>
            <el-option label="给排水" value="给排水"></el-option>
            <el-option label="电气" value="电气"></el-option>
            <el-option label="垃圾回收" value="垃圾回收"></el-option>
            <el-option label="净水设备" value="净水设备"></el-option>
            <el-option label="休闲健身" value="休闲健身"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备位置" prop="location">
          <el-input v-model="updateForm.location" class="newInput"></el-input>
        </el-form-item>
        <el-form-item
            label="保养周期月份"
            prop="keepPeriod"
        >
          <el-input v-model.number="updateForm.keepPeriod" autocomplete="off" class="newInput"></el-input>
        </el-form-item>
        <el-form-item
            label="设备使用年限"
            prop="serviceLife"
        >
          <el-input v-model.number="updateForm.serviceLife" autocomplete="off" class="newInput"></el-input>
        </el-form-item>
        <!--时间选择器-->
        <el-form-item label="设备首次使用时间" prop="startTime">
          <el-date-picker
              class="createRepairsTime"
              v-model="updateForm.startTime"
              align="right"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择首次使用时间"
              :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <!--图片上传,show-file-list是否显示文件列表-->
        <el-form-item label="设备图片">
          <el-upload
              class="avatar-uploader"
              :action="$basePath+'device/updateUploadImages'"
              :show-file-list="false"
              :accept="allowedPicExts"
              :headers="headers"
              :on-success="handleUpdatePicSuccess"
              :before-upload="beforeUpdatePicUpload">
            <img v-if="updateImageUrl" :src="updateImageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <!--因为设备到期后，status会自动变成‘过期’，因此这里选状态就不合理，不过先别删除它-->
<!--        <el-form-item label="设备状态" prop="status">-->
<!--          <el-select v-model="updateForm.status" placeholder="请选择状态" class="newSelect">-->
<!--            <el-option label="正常" value="正常"></el-option>-->
<!--            <el-option label="异常" value="异常"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <!-- 设备保养手册应该可上传图片或上传pdf ，但这里只上传文字-->
        <el-form-item label="设备保养手册" prop="keepStandard">
          <el-input type="textarea" v-model="updateForm.keepStandard" class="newTextarea"></el-input>
        </el-form-item>
        <!-- 备注-->
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="updateForm.remark" class="newTextarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleByUpdate = false">取 消</el-button>
        <el-button type="primary" @click="commit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import axios from "axios";
import response from "core-js/internals/is-forced";
export default {
  props: {},
  components: {//3.注册组件
  },
  filters: {//过滤器，时间格式调整
    formatDateTime(value) {
      if (!value) return '';
      const date = new Date(value);
      // 使用UTC方法，避免时区转换
      const year = date.getUTCFullYear();
      const month = (date.getUTCMonth() + 1).toString().padStart(2, '0');
      const day = date.getUTCDate().toString().padStart(2, '0');
      const hours = date.getUTCHours().toString().padStart(2, '0');
      const minutes = date.getUTCMinutes().toString().padStart(2, '0');
      return `${year}-${month}-${day} `;
    /*  其实这里如果按yyyy-MM-dd HH:mm显示的话，后面的HH:mm为00:00，要想改为整除显示后端查出来的时间的话，
      要改后端配置为：spring.jackson.date-format=yyyy-MM-dd HH:mm
      这样按年月日查询就不行了，所以就让他显示到日就行
     */
    },
    formatDate(value) {
      if (!value) return ''
      const date = new Date(value)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    }
  },
  name: "EquipmentInfo",//与组件名一样
  // 筛选下拉框
  data() {
    let that=this;//data里面无法使用this
    return {
      headers:{"token":window.localStorage.token},
      maxFileSize: 1024*1024*10,//10M
      allowedPicExts:'.jpg,.jpeg,.png,.webp,.gif',//允许的上传图片拓展名
      imageUrl: '',//add上传图片预览url
      updateImageUrl: '',//修改时上传图片预览URL
      addFileList:[],//添加设备信息时的文件上传列表
      updateFileList:[],//修改设备信息时的文件上传列表
      searchAdminRepairs:{//多条件查询的条件在这里,为配合watch实现搜索栏为空自动重新搜索功能，这里默认值为null
        deviceName:null,
        deviceModel:null,
        deviceType:null,
        startTime:null,
        status:null,
        creatTime:null,
        updateTime:null,
      },
      showAlert:false,//alert默认隐藏
      dialogFormVisible: false,
      dialogFormVisibleByAdd:false,
      dialogFormVisibleByUpdate:false,
      addForm: {//add form表单交到这
        deviceName:'',
        deviceModel:'',
        deviceType:'',
        location:'',
        keepPeriod:'',
        keepStandard:'',
        startTime:'',
        serviceLife:'',
        status:'正常',//默认选中
        creatBy:'',//这个要从session取
        remark:'',
        inboundPic:{
          devicePic:'',
          remark:'',
          enable:'',
          creatBy:'',
        }
      },
      updateForm: {//update form表单交到这
        id:'',
        deviceName:'',
        deviceModel:'',
        deviceType:'',
        location:'',
        keepPeriod:'',
        keepStandard:'',
        startTime:'',
        createTime:'',
        serviceLife:'',
        status:'正常',//默认选中
        creatBy:'',//这个要从session取
        remark:'',
        updateBy:'',//这个要从session取
        inboundPic:{
          id:'',//inboundPic的id
          devicePic:'',//图片名
          remark:'',//备注，没啥用
          enable:'',//禁用状态
          creatBy:'',//创建图片的员工id
          updateBy:'',//修改图片的员工id
          deviceId:'',//对应设备id
        }
      },
      typeOptions: [{//前端写死类型，
        value: '监控',
        label: '监控'
      }, {
        value: '消防',
        label: '消防'
      },
      {
        value: '照明',
        label: '照明'
      },
      {
        value: '电气',
        label: '电气'
      },
      {
        value: '电梯',
        label: '电梯'
      },
      {
        value: '给排水',
        label: '给排水'
      },
      {
        value: '供暖',
        label: '供暖'
      },
      {
        value: '垃圾回收',
        label: '垃圾回收'
      },
      {
        value: '净水设备',
        label: '净水设备'
      },
      {
        value: '休闲健身',
        label: '休闲健身'
      },
      {
        value: '其他',
        label: '其他'
      },
      ],
      value: '',
      StatusOptions: [{//前端写死，
        value: '正常',
        label: '正常'
      }, {
        value: '过期',
        label: '过期'
      },
      ],
      //日期选择器
      pickerOptions: {
        disabledDate(date) {//判断点选的日期是否禁用，date是选择器里的所有可用日期
          let formatDate = that.$dayjs(date).format('YYYY-MM-DD');//转换选择的日期格式
          let thatCreateTime = that.$dayjs(that.updateForm.creatTime).format('YYYY-MM-DD');//转换creatTime的日期格式
          let currentDate = that.$dayjs().format('YYYY-MM-DD');//当前时间
          if(formatDate < thatCreateTime) {//比较
            return true
          }
          else if(formatDate > currentDate) {
            return true
          }
          return false//最终返回false别忘了
        },
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }
        ]
      },
      //与修改的设备首次使用时间受限制的选择器区分开，这些是多条件查询中的时间选择器不应受限
      pickerOptionsOther: {
        disabledDate(time) {
          return false;//任何日期不禁用
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      //
      value1: '',//组件自带，别删
      value2: '',//组件自带，别删
      tableData: [],
      device:{//这是显示用的表单
        id:'',
        deviceName:'',
        deviceModel:'',
        deviceType:'',
        location:'',
        keepPeriod:'',
        keepStandard:'',
        startTime:'',
        serviceLife:'',
        status:'',
        creatBy:'',
        creatTime:'',
        updatedBy:'',
        updateTime:'',
        remark:'',
        admin:{
          adminName:'',
        },
        user:{
          userName:'',
        },
        inboundPic:{
          devicePic:'',
        },
      },
      currentRow:{//确认删除单行信息，临时存储row的device对象,如果删除可将id传到后端
        id:'',
        deviceName:'',
        deviceModel:'',
        deviceType:'',
        location:'',
        keepPeriod:'',
        keepStandard:'',
        startTime:'',
        serviceLife:'',
        status:'',
        creatBy:'',
        creatTime:'',
        updatedBy:'',
        updateTime:'',
        remark:'',
        admin:{
          adminName:'',
        },
        user:{
          userName:'',
        },
        inboundPic:{
          id:'',
          deviceId:'',
          updateBy:'',
          devicePic:'',
        }
      },
      loading: true, //加载时转圈
      flag: true,//add表单标记布尔值
      flagDelete: false,//选择是否删除布尔标记
      deleteId:'',//将要删除掉的id
      rules: {
        deviceName: [
          { required: true, message: '请输入设备名称', trigger: 'blur' },
          { min: 2, max: 15, message: '设备名称长度应在2到15个字符', trigger: 'blur' }
        ],
        deviceModel: [
          { required: true, message: '请输入设备型号', trigger: 'blur' },
          { pattern: /^[A-Za-z0-9\-_]+$/, message: '设备型号格式不正确', trigger: 'blur' }
        ],
        deviceType: [
          { required: true, message: '请选择设备类型', trigger: 'change' }, // 使用 change 触发时机
        ],
        location: [
          { required: true, message: '请输入设备位置', trigger: 'blur' },
          { min: 2, max: 15, message: '设备位置应在2到15个字符', trigger: 'blur' }
        ],
        keepPeriod: [
          { required: true, message: '保养周期月份不能为空', trigger: 'blur' },
          { type: 'number', message: '保养周期月份必须是数字', trigger: 'blur', transform(value) { return Number(value); } }, // 可选：确保是数字类型（v-model.number 已处理）
          { validator: (rule, value, callback) => {
              if (!Number.isInteger(value)) {
                callback(new Error('保养周期月份必须是整数'));
              } else if (value < 1) {
                callback(new Error('保养周期月份错误'));
              } else {
                callback();
              }
            }, trigger: 'blur'
          },
        ],
        serviceLife: [
          { required: true, message: '设备使用年限不能为空', trigger: 'blur' }, // 必填校验
          {
            validator: (rule, value, callback) => {
              if (value === null || value === undefined || value === '') {
                callback(new Error('设备使用年限不能为空')); // 冗余校验（防止绕过 required）
              } else if (!Number.isInteger(value)) {
                callback(new Error('设备使用年限必须是整数'));
              } else if (value < 1) {
                callback(new Error('设备使用年限最小为1'));
              } else {
                callback(); // 验证通过
              }
            },
            trigger: 'blur' // 触发时机
          },
        ],
        status: [
          { required: true, message: '设备状态不能为空', trigger: 'change' }, // 必填校验
        ],
        startTime: [
          {
            required: true,
            message: '请选择设备首次使用时间',
            trigger: 'change'
          },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('请选择日期'));
              }
              callback();
            },
            trigger: 'change'
          }
        ],
        keepStandard: [
          { max: 50, message: '不能超过50字', trigger: 'blur' }
        ],
        remark: [
          { max: 50, message: '不能超过50字', trigger: 'blur' }
        ],
      }
    }
  },
  watch:{//使用侦听器实现搜索栏为空自动重新搜索，注意repairStatus不选中为空字符串''而不是null
    searchAdminRepairs: {
      handler(newVal) {
        // 检查所有条件是否为空
        const isEmpty = !newVal.deviceName && !newVal.deviceModel && !newVal.deviceType
              && !newVal.startTime && newVal.status === '' && !newVal.creatTime && !newVal.updateTime;
        if (isEmpty) {
          this.getList(1); // 执行查询，pageNum 设为 1
        }
      },
      deep: true, // 深度监听，因为 searchAdminRepairs 是一个对象
    }
  },
  created() {
    this.getList(1)//传一个页码，默认从第一页查
  },
  methods: {
    getList(pageNum) {
      this.loading = false;//取消加载转圈
      /* 往后端传时间时，只传年月日，后端接收时间加上00:00:00
      下面这三个if这么写是为了解决传到后端的时间比前端选择的晚一天的问题，不要删除它！*/
      if(this.searchAdminRepairs.creatTime){
        const date = new Date(this.searchAdminRepairs.creatTime);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        this.searchAdminRepairs.creatTime = `${year}-${month}-${day}`;
      }
      if(this.searchAdminRepairs.updateTime){
        const date = new Date(this.searchAdminRepairs.updateTime);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        this.searchAdminRepairs.updateTime = `${year}-${month}-${day}`;
      }
      if(this.searchAdminRepairs.startTime){
        const date = new Date(this.searchAdminRepairs.startTime);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        this.searchAdminRepairs.startTime = `${year}-${month}-${day}`;
      }
      // 传页码过去，post是第三个，第二个是传对象，get是第二个传参数
      this.$axios.post("device/list",this.searchAdminRepairs,{params:{pageNum:pageNum}}).then((response) => {
        this.tableData = response.data.list;//list里面有数据和分页的参数
      });
      /*说明：
      以创建时间creatTime为例，这里我利用device里的creatTime传一个yyyy-MM-dd到后端，
      后端接收到的creatTime就是yyyy-MM-dd 00:00:00，以这个时间为开始时间，
      然后在后端的deviceServiceImpl里new一个Date对象，修改为yyyy-MM-dd 23:59:59，以这个时间为结束时间，
      使用sql查出当天所有的记录，
      因为是后端统一配置为：spring.jackson.date-format=yyyy-MM-dd，如此查询才能生效*/
    },
    tableRowClassName({row, rowIndex}) {//table方法
      // 如果状态为"过期"，返回error-row类名
      if (row.status === '过期') {
        return 'error-row';
      }
      return '';
    },
    handleAdd(){
      this.dialogFormVisibleByAdd = true
    },
    save() {
      this.$refs.ruleForm.validate((valid) => {//先判断表单是否可以提交
        if (valid) {
          this.flag = true;
        } else {
          this.flag = false;
        }
      });
      if (this.flag) {
      let adminId = (JSON.parse(window.localStorage.getItem("admin"))).id;//谁登陆取谁的id
      this.addForm.creatBy = adminId//应该从token里取，给属性赋值
      this.addForm.inboundPic.creatBy = adminId//应该从token里取，给属性赋值
      this.$axios.post("device/insertDevice",this.addForm).then((response) => {
        const successMessage = response.data.msg; // 提取后端返回的消息
        this.dialogFormVisibleByAdd = false;
        this.getList(1)//再查一次
        this.$message.success(successMessage); // 显示后端返回的消息
      });
      }
    },
    handleUpdate(row) {//修改时显示原来的数据
      let adminId = (JSON.parse(window.localStorage.getItem("admin"))).id;//谁登陆取谁的id
      this.dialogFormVisibleByUpdate = true;
      this.updateForm.updateBy = adminId//从token取,写死的话就是1，具体如下代码：
      this.$axios.post('device/getDeviceByUpdate', { id: row.id })
          .then((response) => {
            this.updateForm = response.data.updateFrom;
            // 处理图片预览
            this.updateImageUrl = this.updateForm.inboundPic?.devicePic
                ? `http://localhost:8080/static/uploadImages/${this.updateForm.inboundPic.devicePic}`
                : '';
            // 确保createTime存在（使用响应数据或当前时间），自动填充当前时间，避免提交时因必填字段缺失导致报错。
            if (!this.updateForm.createTime) {
              this.updateForm.createTime = new Date().toISOString();
            } else {
              // 如果后端返回的是字符串格式，确保转为ISO格式,确保前端组件正确解析
              this.updateForm.createTime = new Date(this.updateForm.createTime).toISOString();
            }
            // 处理startTime（优先使用原有值）
            if (!this.updateForm.startTime) {
              // 如果startTime为空，默认设置为createTime的日期（去掉时间部分）
              const createDate = new Date(this.updateForm.createTime);
              this.updateForm.startTime = createDate.toISOString().split('T')[0];
            } else {
              // 如果已有值，确保格式正确（只保留日期部分）
              this.updateForm.startTime = new Date(this.updateForm.startTime).toISOString().split('T')[0];
            }
          })
          .catch(error => {//异常处理
            this.$message.error('获取设备信息失败');
          });
    },
    commit(){//修改提交，真的去修改
      this.$refs.ruleForm.validate((valid) => {//先判断表单是否可以提交
        if (valid) {
          this.flag = true;
        } else {
          this.flag = false;
        }
      });
      if(this.flag) {
        this.updateForm.updateBy = 1;
        this.updateForm.status = '正常'//默认正常，在添加时取消选择状态的select选择框
        let adminId = (JSON.parse(window.localStorage.getItem("admin"))).id;//谁登陆取谁的id
        this.updateForm.updateBy = adminId//赋值修改人id
        //给inboundPic的id赋值
        this.updateForm.inboundPic.deviceId = this.updateForm.id//给inboundPic的deviceId赋值
        this.$axios.post("device/updateDevice",this.updateForm).then((response) => {
          const successMessage = response.data.msg;
          this.dialogFormVisibleByUpdate = false;
          this.getList(1);
          this.$message.success(successMessage);
        });
      }
    },
    handleDelete(row) {
      this.currentRow = row;
      this.$confirm(
          `确定要删除 <strong>[${row.deviceName || '未命名设备'}]</strong> 吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true
          }
      )
          .then(() => {//去后段逻辑删除,把要删除的device对象传到后端
            this.$axios.post("device/delete",this.currentRow)
                .then((res) => {
                  this.getList(1);
                  this.$message.success(res.data.msg || "删除成功");
                })
                .catch(() => {
                  this.$message.error("删除失败");
                });
          })
          .catch(() => {// 用户点击取消时的处理，解决"Uncaught (in promise) cancel"错误，如果用户点取消，会报错
            // this.$message.info('已取消删除操作');//不必提示了
          });
    },
    handleLook(row) {//查看手册
      this.dialogFormVisible = true
      this.$axios.get(`device/getStandard?id=${row.id}`)
          .then((response) => {
            this.device = response.data.device;
          });
    },
    handlePageNumChange(pageNum) {//更改页码
      this.getList(pageNum);
    },
    //添加图片上传成功方法
    handlePicSuccess(response, file) {
      if (response.code === 500) { // 明确判断失败
        this.$message.error(response.msg || "图片上传失败");
        return false;
      }
      this.imageUrl = URL.createObjectURL(file.raw);//上传成功后预览图片
      // 将返回的图片路径赋值给要提交的表单addForm.inboundPic.devicePic
      this.addForm.inboundPic.devicePic = response.fileName;
    },
    //添加图片上传之前校验大小格式方法
    beforePicUpload(file) {
      this.imageUrl = ""//清空之前上传的图片，显示当前最新上传的图片进行预览
      let dotIndex = file.name.lastIndexOf(".")//取拓展名
      if(dotIndex === -1) {//没有拓展名
        this.$message.error("上传图片格式错误")
        return false;
      }
      let ext = file.name.substr(dotIndex);
      if(!(","+this.allowedPicExts+",").includes(","+ext+",")){//把",xxx,"完整包进去
        this.$message.error("上传图片只能是:"+this.allowedPicExts+"格式")
        return false;
      }
      if(file.size > this.maxFileSize){
        this.$message.error("图片不能超过"+this.maxFileSize/(1024*1024)+"MB")
        return false;
      }
      return true;
    },
    //update//////
    //修改设备图片的上传
    //图片上传成功方法
    handleUpdatePicSuccess(response, file) {
      // 1. 明确处理失败情况
      if (response.code === 500) {
        this.$message.error(response.msg || "图片上传失败");
        return false;
      }
      // 2. 确保inboundPic对象存在（Vue响应式初始化）
      if (!this.updateForm.inboundPic) {
        this.$set(this.updateForm, 'inboundPic', {
          devicePic: '',
          remark: '',
          enable: true
        });
      }
      // 3. 安全设置属性
      this.updateForm.inboundPic.devicePic = response.fileName || '';
      // 4. 图片预览（增加URL安全释放）
      if (this.updateImageUrl) {
        URL.revokeObjectURL(this.updateImageUrl); // 释放之前创建的URL
      }
      this.updateImageUrl = file?.raw
          ? URL.createObjectURL(file.raw)
          : '';
    },
    // handleUpdatePicSuccess(response, file) {
    //   if (response.code === 500) { // 明确判断失败
    //     this.$message.error(response.msg || "图片上传失败");
    //     return false;
    //   }
    //   this.updateImageUrl = URL.createObjectURL(file.raw);//上传成功后预览图片
    //   // 将返回的图片路径赋值给要提交的表单addForm.inboundPic.devicePic
    //   this.updateForm.inboundPic.devicePic = response.fileName;
    // },
    //图片上传之前校验大小格式方法
    beforeUpdatePicUpload(file) {
      this.updateImageUrl = ""//清空之前上传的图片，显示当前最新上传的图片进行预览
      let dotIndex = file.name.lastIndexOf(".")//取拓展名
      if (dotIndex == -1) {//没有拓展名
        this.$message.error("上传图片格式错误")
        return false;
      }
      let ext = file.name.substr(dotIndex);
      if(!(","+this.allowedPicExts+",").includes(","+ext+",")){//把",xxx,"完整包进去
        this.$message.error("上传图片只能是:"+this.allowedPicExts+"格式")
        return false;
      }
      if(file.size > this.maxFileSize){
        this.$message.error("图片不能超过"+this.maxFileSize/(1024*1024)+"MB")
        return false;
      }
      return true;
    },
  },
}
</script>
<!--遵循该模版样式-->
<style>
.pageNum{
  display: flex;
  justify-content: center; /* 水平居中 */
  padding-top: 30px;
}
.updateRepairsTime{
  margin-left: 5px;
}
el-table{
  text-align: center;
}
.el-table th > .cell {
  text-align: center;
}
.el-table .cell {
  text-align: center;
}
.el-table .warning-row {
  background: oldlace;
}
.el-table .success-row {
  background: #f0f9eb;
}
el-input{
  width: 700px;
}
/* 隐藏表头的复选框 */
.hide-header-checkbox .el-checkbox {
  display: none;
}
.newInput{
  width: 250px;
}
.newSelect{
  width: 130px;
}
.newTextarea{
  width: 250px;
}
/* 预览大图的样式修改，自定义预览窗口的尺寸 */
.custom-image >>> .el-image-viewer__mask {
  background-color: rgba(0, 0, 0, 0.8);
}
.custom-image >>> .el-image-viewer__wrapper {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 2000;
}
/*用于设置预览窗口的最大宽度和高度*/
.custom-image >>> .el-image-viewer__container {
  max-width: 50%;
  max-height: 50%;
}
.custom-image >>> .el-image-viewer__canvas {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
.custom-image >>> .el-image-viewer__canvas img {
  max-width: 100%;
  max-height: 100%;
}
/*图片上传组件样式*/
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
.el-table .error-row {
  background-color: #ffdddd; /* 如果设备过期该行变为浅红色背景 */
}
/* 鼠标悬停在设备图片上光标变为放大镜 */
.custom-image img:hover {
  cursor: zoom-in;
}
</style>